In [2]:
%run ../common.ipynb
from skimage.feature import hog


Populating the interactive namespace from numpy and matplotlib
WARNING: pylab import has clobbered these variables: ['imread', 'imsave']
`%matplotlib` prevents importing * from pylab and numpy

In [3]:
size = 256
img = np.zeros((size,size), dtype=np.uint8)
t = linspace(start=0, stop=50*pi, endpoint=False, num=size)s
x,y = meshgrid(t, t)
img[:,:] = 127 + 127*sin(x+y)
#img[:,:] = 127 + 127*sin(sqrt((80-x)**2+(80-y)**2))
#img = rot90(img)
gimshow(img)
a, hog_img = hog(img, orientations=8, cells_per_block=(4,4), visualise=True)
imshow(hog_img);



In [187]:
yy = ndimage.sobel(img, axis=0)
xx = ndimage.sobel(img, axis=-1)
angles = arctan2(xx,yy) / pi * 180 # in degrees
%matplotlib qt
imshow(angles, cmap='hot')


Out[187]:
(<matplotlib.figure.Figure at 0x10d390b38>,
 <matplotlib.axes._subplots.AxesSubplot at 0x10c6a3358>,
 <matplotlib.image.AxesImage at 0x109668208>)

In [201]:
plt.hist(angles.flatten(), bins=360, normed=True);



In [76]:
def anglehist(img):
    "Plot angles in image as histogram."
    grad = gradient(img)
    angles = arctan2(grad[0], grad[1]) / pi * 180
    amax = angles.max()
    amin = angles.min()
    r = amax - amin + 1
    figure()
    h = plt.hist(angles.flatten(), bins=r, range=(amin, amax), normed=True)
    xlim(amin, amax)
    return h

In [67]:
anglehist(img);


plt.rcParams['image.interpolation'] = 'none' img = np.zeros((size,size)) img[:,:] = 127 + 127sin(x-3y) img = img.astype(np.int) imshow(img[0:10,0:10]) colorbar() figure() grad = gradient(img) angle = arctan2(img[0], img[1]) / pi * 180 figure() plt.hist(angle);


In [179]:
img = imread('../FY3490/mp.png')
a, hog_img = hog(img, visualise=True)
anglehist(img)
img = smooth(img)
anglehist(img);



In [405]:
figure(figsize=(14,14))
plt.bar(range(180), h, width=0.8)


Out[405]:
<Container object of 180 artists>

In [414]:
hf = ndimage.uniform_filter1d(h, size=9)
figure(figsize=(14,14))
plt.bar(range(180), hf)
np.where(hf > hf.max()*0.9)


Out[414]:
(array([22, 29, 30, 59, 60, 67]),)

In [2]:
def g():
    ori = 180 # every 2 degrees
    img = imread('mp.png')
    # histogram of gradient 20 orientations
    ihog = hog(img, orientations=ori)
    # sum up magnitudes for each orientation
    h = np.zeros((ori))
    for i in range(ori):
        h[i] = ihog[i::ori].sum()
    plt.bar(range(ori), h)
    h2 = np.where(h > h.max()*0.8, 0, h) # remove the highest (0,45,90,135 degrees)
    figure()
    plt.bar(range(ori), h2)

In [13]:
%lprun -f hog2 hog2(img, orientations=180)

In [11]:
def hog2(image, orientations=9, pixels_per_cell=(8, 8),
        cells_per_block=(3, 3), visualise=False, normalise=False):
    """Extract Histogram of Oriented Gradients (HOG) for a given image.

    Compute a Histogram of Oriented Gradients (HOG) by

        1. (optional) global image normalisation
        2. computing the gradient image in x and y
        3. computing gradient histograms
        4. normalising across blocks
        5. flattening into a feature vector

    Parameters
    ----------
    image : (M, N) ndarray
        Input image (greyscale).
    orientations : int
        Number of orientation bins.
    pixels_per_cell : 2 tuple (int, int)
        Size (in pixels) of a cell.
    cells_per_block  : 2 tuple (int,int)
        Number of cells in each block.
    visualise : bool, optional
        Also return an image of the HOG.
    normalise : bool, optional
        Apply power law compression to normalise the image before
        processing.

    Returns
    -------
    newarr : ndarray
        HOG for the image as a 1D (flattened) array.
    hog_image : ndarray (if visualise=True)
        A visualisation of the HOG image.

    References
    ----------
    * http://en.wikipedia.org/wiki/Histogram_of_oriented_gradients

    * Dalal, N and Triggs, B, Histograms of Oriented Gradients for
      Human Detection, IEEE Computer Society Conference on Computer
      Vision and Pattern Recognition 2005 San Diego, CA, USA

    """
    image = np.atleast_2d(image)

    """
    The first stage applies an optional global image normalisation
    equalisation that is designed to reduce the influence of illumination
    effects. In practice we use gamma (power law) compression, either
    computing the square root or the log of each colour channel.
    Image texture strength is typically proportional to the local surface
    illumination so this compression helps to reduce the effects of local
    shadowing and illumination variations.
    """

    if image.ndim > 2:
        raise ValueError("Currently only supports grey-level images")

    if normalise:
        image = sqrt(image)

    """
    The second stage computes first order image gradients. These capture
    contour, silhouette and some texture information, while providing
    further resistance to illumination variations. The locally dominant
    colour channel is used, which provides colour invariance to a large
    extent. Variant methods may also include second order image derivatives,
    which act as primitive bar detectors - a useful feature for capturing,
    e.g. bar like structures in bicycles and limbs in humans.
    """

    if image.dtype.kind == 'u':
        # convert uint image to float
        # to avoid problems with subtracting unsigned numbers in np.diff()
        image = image.astype('float')

    gx = np.zeros(image.shape)
    gy = np.zeros(image.shape)
    gx[:, :-1] = np.diff(image, n=1, axis=1)
    gy[:-1, :] = np.diff(image, n=1, axis=0)

    """
    The third stage aims to produce an encoding that is sensitive to
    local image content while remaining resistant to small changes in
    pose or appearance. The adopted method pools gradient orientation
    information locally in the same way as the SIFT [Lowe 2004]
    feature. The image window is divided into small spatial regions,
    called "cells". For each cell we accumulate a local 1-D histogram
    of gradient or edge orientations over all the pixels in the
    cell. This combined cell-level 1-D histogram forms the basic
    "orientation histogram" representation. Each orientation histogram
    divides the gradient angle range into a fixed number of
    predetermined bins. The gradient magnitudes of the pixels in the
    cell are used to vote into the orientation histogram.
    """

    magnitude = sqrt(gx**2 + gy**2)
    orientation = arctan2(gy, gx) * (180 / pi) % 180

    sy, sx = image.shape
    cx, cy = pixels_per_cell
    bx, by = cells_per_block

    n_cellsx = int(np.floor(sx // cx))  # number of cells in x
    n_cellsy = int(np.floor(sy // cy))  # number of cells in y

    # compute orientations integral images
    orientation_histogram = np.zeros((n_cellsy, n_cellsx, orientations))
    subsample = np.index_exp[cy // 2:cy * n_cellsy:cy,
                             cx // 2:cx * n_cellsx:cx]
    for i in range(orientations):
        #create new integral image for this orientation
        # isolate orientations in this range

        temp_ori = np.where(orientation < 180.0 / orientations * (i + 1),
                            orientation, -1)
        temp_ori = np.where(orientation >= 180.0 / orientations * i,
                            temp_ori, -1)
        # select magnitudes for those orientations
        cond2 = temp_ori > -1
        temp_mag = np.where(cond2, magnitude, 0)

        mask = np.ones((cy,cx))
        temp_filt = ndimage.convolve(temp_mag, mask/9.)
        orientation_histogram[:, :, i] = temp_filt[subsample]

    # now for each cell, compute the histogram
    hog_image = None

    if visualise:
        from skimage import draw

        radius = min(cx, cy) // 2 - 1
        hog_image = np.zeros((sy, sx), dtype=float)
        for x in range(n_cellsx):
            for y in range(n_cellsy):
                for o in range(orientations):
                    centre = tuple([y * cy + cy // 2, x * cx + cx // 2])
                    dx = radius * cos(float(o) / orientations * np.pi)
                    dy = radius * sin(float(o) / orientations * np.pi)
                    rr, cc = draw.line(int(centre[0] - dx),
                                       int(centre[1] - dy),
                                       int(centre[0] + dx),
                                       int(centre[1] + dy))
                    hog_image[rr, cc] += orientation_histogram[y, x, o]

    """
    The fourth stage computes normalisation, which takes local groups of
    cells and contrast normalises their overall responses before passing
    to next stage. Normalisation introduces better invariance to illumination,
    shadowing, and edge contrast. It is performed by accumulating a measure
    of local histogram "energy" over local groups of cells that we call
    "blocks". The result is used to normalise each cell in the block.
    Typically each individual cell is shared between several blocks, but
    its normalisations are block dependent and thus different. The cell
    thus appears several times in the final output vector with different
    normalisations. This may seem redundant but it improves the performance.
    We refer to the normalised block descriptors as Histogram of Oriented
    Gradient (HOG) descriptors.
    """

    n_blocksx = (n_cellsx - bx) + 1
    n_blocksy = (n_cellsy - by) + 1
    normalised_blocks = np.zeros((n_blocksy, n_blocksx,
                                  by, bx, orientations))

    for x in range(n_blocksx):
        for y in range(n_blocksy):
            block = orientation_histogram[y:y + by, x:x + bx, :]
            eps = 1e-5
            normalised_blocks[y, x, :] = block / sqrt(block.sum()**2 + eps)

    """
    The final step collects the HOG descriptors from all blocks of a dense
    overlapping grid of blocks covering the detection window into a combined
    feature vector for use in the window classifier.
    """

    if visualise:
        return normalised_blocks.ravel(), hog_image
    else:
        return normalised_blocks.ravel()

In [457]:
np.where(h > h.max()*0.09)


Out[457]:
(array([  0,  45,  90, 135]),)

In [459]:
%matplotlib qt
imshow(img)


Out[459]:
<matplotlib.image.AxesImage at 0x1569bc240>

In [19]:
def anglehist(img):
    "Plot angles in image as histogram."

    # imports
    from numpy import zeros_like, arctan2, ravel, histogram, pi

    # as signed integer (dx,dy negative values too)
    img = img.astype(np.int16)

    # calculate difference in x-y direction
    dx = zeros_like(img)
    dy = zeros_like(img)
    dx[:,1:-1] = img[:,2:] - img[:,0:-2]
    dy[1:-1,:] = img[2:,:] - img[0:-2,:]

    #magnitude = sqrt(dx**2+dy**2)

    # calculate angle of gradient
    angles = arctan2(dy, dx, ) / pi * 180 % 180

    # exclude weak orientations
    #angles[magnitude < magnitude.mean()] = 0
    
    # exclude n*45 angles
    mask = ~((angles == 0) +
             (angles == 45) +
             (angles == 90) +
             (angles == 135))
    angles = ravel(angles[mask]) # flatten also
    
    # calculate histogram of angles
    return histogram(angles, bins=180, range=(0,180))

In [ ]:
%timeit anglehist(img)

In [ ]:
%lprun -s -f anglehist anglehist(img)

In [ ]:
from skimage import filter
img = imread('mp.png')
img = filter.threshold_adaptive(img, 3)

In [14]:
sy = img.shape[0] // 40
sx = img.shape[1] // 40
for i in range(20,25):
    for j in range(5,10):
        temp_img = img[i*sy:(i+1)*sy, j*sx:(j+1)*sx]
        figure(figsize=(14,7))
        subplot(122)
        matplotlib.pylab.imshow(temp_img)
        #h = anglehist(temp_img)
        h = hog(temp_img, orientations=180)
        hh = np.zeros(180)
        for x in range(180):
            if x==0 or x==45 or x==90 or x==135:
                continue
            hh[x] = h[x::180].sum()
        subplot(121)
        plt.bar(range(180), hh)
        t = 'cm:{:3.1f}, mean:{:0.2}, var:{:0.2}'.format(ndimage.center_of_mass(hh)[0],hh.mean(),hh.var())
        title(t)


/Users/arve/.virtualenvs/3.4/lib/python3.4/site-packages/matplotlib/pyplot.py:424: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
  max_open_warning, RuntimeWarning)

In [17]:
img = np.zeros((size,size))
img[:,:] = 127 + 127*sin(x-3*y)
imshow(img)
figure()
grad = gradient(img)
angle = arctan2(img[0], img[1]) / pi * 180
figure()
plt.hist(angle);


<matplotlib.figure.Figure at 0x108cad208>

In [ ]:
img = imread('../FY3490/mp.png')
a, hog_img = hog(img, visualise=True)

In [20]:
anglehist(img)
img = smooth(img)
anglehist(img);

In [23]:
ori = 180 # every 2 degrees
img = imread('mp.png')
# histogram of gradient 20 orientations
ihog = hog(img, orientations=ori)
# sum up magnitudes for each orientation
h = np.zeros((ori))
for i in range(ori):
    h[i] = ihog[i::ori].sum()
plt.bar(range(ori), h)
h2 = np.where(h > h.max()*0.8, 0, h) # remove the highest (0,45,90,135 degrees)
figure()
plt.bar(range(ori), h2)


Out[23]:
<Container object of 180 artists>

In [26]:
hf = ndimage.uniform_filter1d(h, size=9)
figure(figsize=(14,14))
plt.bar(range(180), hf)
np.where(hf > hf.max()*0.9)


Out[26]:
(array([0, 1, 2, 3]),)

In [24]:
step = 10
for i in range(0,180,step):
    ti = np.where(ang<i+step, ang, -1)
    ti = np.where(ang>=i, ti, -1)
    imshow(ti)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-24-6ef8d835f23c> in <module>()
      1 step = 10
      2 for i in range(0,180,step):
----> 3     ti = np.where(ang<i+step, ang, -1)
      4     ti = np.where(ang>=i, ti, -1)
      5     imshow(ti)

NameError: name 'ang' is not defined